﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using Model;

namespace Observer
{
    public class Mailing : IMailing
    {
        private static readonly List<IMessageCallback> burglars
                   = new List<IMessageCallback>();

        public static void NotifyActivity(PalaceActivity activity){
            burglars.ForEach(delegate(IMessageCallback callback){
                if (((ICommunicationObject)callback).State == CommunicationState.Opened){
                    callback.PalaceActivity(activity);
                }
                else{
                    Unsubcribe(callback);
                }
            });
        }

        public static void NotifyNewPalace(Palace palace){
            burglars.ForEach(delegate(IMessageCallback callback){
                if (((ICommunicationObject)callback).State == CommunicationState.Opened){
                    callback.PalaceAdded(palace);
                }
                else{
                    Unsubcribe(callback);
                }
            });
        }
        public static void NotifyPalaceRemove(Palace palace){
            burglars.ForEach(delegate(IMessageCallback callback){
                if (((ICommunicationObject)callback).State == CommunicationState.Opened){
                    callback.PalaceRemoved(palace);
                }
                else{
                    Unsubcribe(callback);
                }
            });
        }

        public void Subscribe(String Name){
            try{
                var callback = OperationContext.Current.GetCallbackChannel<IMessageCallback>();
                if (!burglars.Contains(callback))
                    lock (burglars){
                        burglars.Add(callback);
                    }
            }
            catch
            {

            }
        }

        public void Unsubscribe(){
            try{
                var callback = OperationContext.Current.GetCallbackChannel<IMessageCallback>();
                if (burglars.Contains(callback))
                    Unsubcribe(callback);
            }
            catch
            {

            }
        }



        public static void Alert(InvasionAlert alert){
            burglars.ForEach(delegate(IMessageCallback callback){
                if (((ICommunicationObject)callback).State == CommunicationState.Opened){
                    callback.PalaceBurglarAlert(alert);
                }
                else{
                    Unsubcribe(callback);
                }
            });
        }

        private static void Unsubcribe(IMessageCallback callback){
            lock (burglars)
            {
                burglars.Remove(callback);
            }
        }
    }
}
